//
// This file is part of the GNU ARM Eclipse distribution.
// Copyright (c) 2014 Liviu Ionescu.
//

#include "Timer.h"
#include "xparameters.h"

volatile Timer::ticks_t Timer::ms_delayCount;
volatile uint32_t systick;

volatile uint32_t* base_timer = (uint32_t*) XPAR_TIMER_0_BASEADDR;

#define TIMER_CASC	(1<<11)
#define TIMER_ENALL	(1<<10)
#define TIMER_PWMA0	(1<<9)
#define TIMER_T0INT	(1<<8)
#define TIMER_ENT0	(1<<7)
#define TIMER_ENIT0	(1<<6)
#define TIMER_LOAD0	(1<<5)
#define TIMER_ARHT0	(1<<4)
#define TIMER_CAPT0	(1<<3)
#define TIMER_GENT0	(1<<2)
#define TIMER_UDT0	(1<<1)
#define TIMER_MDT0	(1<<0)

void Timer::start() {
	*(base_timer) = 0;			// TCSR0
	*(base_timer+1) = 100000;		// TLR0	(1ms)
	*(base_timer+2) = 0;			// TCR0

	*(base_timer) |= TIMER_T0INT;	// clear interrupt
	*(base_timer) |= TIMER_ENIT0 | TIMER_LOAD0 | TIMER_ARHT0 | TIMER_UDT0;	// en int, load tim, auto reload, count down
	*(base_timer) &= ~ TIMER_LOAD0;
	*(base_timer) |= TIMER_ENT0;		// enable timer
}

// ----------------------------------------------------------------------------

void Timer::sleep(ticks_t ticks) {
	ms_delayCount = ticks;

	// Busy wait until the SysTick decrements the counter to zero.
	while (ms_delayCount != 0u)
		;
}

// ----- SysTick_Handler() ----------------------------------------------------

extern "C" void SysTick_Handler(void) {
	*(base_timer) |= TIMER_T0INT;
	systick++;
	Timer::tick();
}

// ----------------------------------------------------------------------------
